package com.checkcode.servlets;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ImageServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//图片缓冲区(宽,高,颜色)
		BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
		//获取画笔
		Graphics g = bi.getGraphics();
		//设置画笔颜色
		g.setColor(new Color(200,150,255));
		//填充矩形(x,y,width,height)
		g.fillRect(0, 0, 68, 22);
		//字符数组,验证码内容
		char[] ch="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
		//利用随机数生成随机下标,从而生成随机验证码
		Random r = new Random();
		int len=ch.length,index;
		//字符缓冲,存储生成的验证码
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 4; i++) {
			index = r.nextInt(len);
			//随机设置字体颜色
			g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255)));
			//绘制字符串(String,x,y)
			g.drawString(ch[index]+"", (i*15)+3, 18);
			//将字符加入缓冲区
			sb.append(ch[index]);
		}
		HttpSession session = req.getSession();
		//将生成的验证码存入session
		session.setAttribute("code", sb.toString());
		//将图片缓冲中生成的最终图片传送回页面
		ImageIO.write(bi, "JPG", resp.getOutputStream());
	}
}
